import Vue from 'vue';
import { Toast } from 'vant';
Vue.use(Toast);

// 获取URL地址参数
const getUrlParam = name => {
  let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
  let r = window.location.search.substr(1).match(reg);
  if (r !== null) return decodeURIComponent(r[2]);
  return null;
};

// 获取code值对应文字
const errorCode = code => {
  let errorText = '';
  let language = localStorage.getItem('language') || 'zh';
  let codeValue = localStorage.getItem('errorCode');
  codeValue = codeValue ? JSON.parse(codeValue) : {};
  errorText = codeValue[language][code];
  return errorText;
};

// 根据接口返回的message值码弹出对应的操作信息
const toastFn = (code, duration = 1000) => {
  let message = '';
  let language = localStorage.getItem('language');
  let codeValue = localStorage.getItem('errorCode');
  codeValue = codeValue ? JSON.parse(codeValue) : {};
  message = codeValue[language][code];
  Toast({
    message,
    duration
  });
};
Vue.prototype.$toastFn = toastFn;

// 日期格式化处理
Date.prototype.Format = function (fmt) {
  //author: meizz
  let o = {
    'M+': this.getMonth() + 1, //月份
    'd+': this.getDate(), //日
    'h+': this.getHours(), //小时
    'm+': this.getMinutes(), //分
    's+': this.getSeconds(), //秒
    'q+': Math.floor((this.getMonth() + 3) / 3), //季度
    S: this.getMilliseconds() //毫秒yarui
  };
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
  for (let k in o)
    if (new RegExp('(' + k + ')').test(fmt))
      fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length));
  return fmt;
};

// 函数防抖
const debounceFn = (fn, delay) => {
  let debounceTimer = null;
  function debounce(fn, delay) {
    if (debounceTimer) {
      clearTimeout(debounceTimer);
    }
    debounceTimer = setTimeout(() => {
      debounceTimer = null;
      fn();
    }, delay);
  }
  debounce(fn, delay);
};
Vue.prototype.$debounceFn = debounceFn;

export { getUrlParam, errorCode };
